package com.newcoder.community.serverce;

import com.newcoder.community.dao.CommentMapper;
import com.newcoder.community.dao.DisCussPostMapper;
import com.newcoder.community.pojo.Comment;
import com.newcoder.community.utill.CommunityConstant;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Isolation;
import org.springframework.transaction.annotation.Propagation;
import org.springframework.transaction.annotation.Transactional;

import java.util.List;

@Service
public class CommentServiceImpl implements CommentService, CommunityConstant {
    @Autowired
    private CommentMapper commentMapper;
    @Autowired
    private DiscussPostService discussPostService;
    @Override
    public List<Comment> selectCommentByEntity(int entityType, int entityId, int offset, int limit) {
        return commentMapper.selectCommentByEntity(entityType,entityId,offset,limit);
    }

    @Override
    public int selectCountByEntity(int entityType, int entityId) {
        return commentMapper.selectCountByEntity(entityType,entityId);
    }

    @Override


    /**
     * 事务管理
     * 当调用插入方法时，增加discussPost中CommentCount数目
     */
    @Transactional(isolation = Isolation.READ_COMMITTED,propagation = Propagation.REQUIRED)
    public int insertComment(Comment comment) {
        if(comment==null){
            throw new IllegalArgumentException( "参数不能为空");
        }
        int i1 = commentMapper.insertComment(comment);
        if(comment.getEntityType()==ENTITY_TYPE_POST){
            int i = commentMapper.selectCountByEntity(comment.getEntityType(),comment.getEntityId());
            discussPostService.updateCommentCount(comment.getEntityId(),i);
        }
        return i1;
    }
}
